'''
Created on Sep 28, 2012

@author: johnny
'''
import unittest, re, os, sys
from utils import configer
from errors import error

import cases

CASE_PATH = os.path.split(cases.__file__)[0]
#CASE_PATH = '../cases'

def get_case_pack():
    cfg = configer.Configer()
    cfg.set_config_file()
    cfg.parse_config_file()
    
    return cfg.get_config_value('common', 'casepackage')
  
CASE_PREFIX = get_case_pack() + '.'


def get_cases_base_name(path=CASE_PATH):
    m_name = []
    patt_str = ".*py$"
    pattern = re.compile(patt_str)
    files = os.listdir(path)
    for item in files:
        if re.match(pattern, item):
            if "__init__" not in item:
                m_name.append(item.split(".")[0])
    return m_name

def get_cases_name(path=CASE_PATH):
    m_name = get_cases_base_name()
    return [CASE_PREFIX + i for i in m_name]

class Test(object):
    def __init__(self):
        self.suite = unittest.TestSuite()
        self.result = unittest.TestResult()
    
    #deprecated just after finished
    def get_all_test(self):
        m_name = get_cases_name()
        loader = unittest.TestLoader()
        self.suite = loader.loadTestsFromNames(m_name)
    
    #deprecated
    def add_bat_test(self, datalist, testcase):
        pass
    
    def add_test_by_name(self, name):
        self.test_name = name
        loader = unittest.TestLoader()
        print "Loadding...", CASE_PREFIX + name
        
        try:
            try:
                self.suite = loader.loadTestsFromName(CASE_PREFIX + name)
            except ImportError:
                raise error.CommonError("Load test case failed: %s" % name)
            print "Done."
        except AttributeError:
            msg = "The test case %s cannot be found!" % name
            raise error.CommonError(msg)
    
    def get_results(self):
        return self.result
    
    def get_test_name(self):
        return self.test_name
    
    def run_test(self):
        self.get_test_name()
        if not self.suite.countTestCases():
            raise error.CommonError("No tests to run, load the test failed maybe!")
        self.result =  \
        unittest.TextTestRunner(stream = sys.stdout).run(self.suite)
        
    def load_module_from_file(self, name):
        return __import__(name, fromlist=['cases'])
        
class Case(unittest.TestCase):
    def __init__(self, name, description=""):
        self.test_name = name
        self.description = description
        